/************************************************************************
*File Name: client_transfile.c
*Author: wsy
*Created Time: 2023年06月21日 星期三 11时06分29秒
*Describtion: 
************************************************************************/
#include "client_transfile.h"

int recvN(int netfd, void* buf, int length)
{                                        
    int total = 0;      // 已经recv的字节数
    char* p = (char*)buf;                
    while(total < length)                
    {                                    
        int ret = recv(netfd, p + total, length - total, 0);
        if(ret == 0)                     
        {                                
            return -1;                   
        }                                
        total += ret;                    
    }                                    
                                         
    return 0;                            
} 

int recvFile(const char* filename, int netfd) {
    // open 并获得文件长度
    int fd = open(filename, O_RDWR | O_CREAT | O_APPEND , 0666);
    struct stat statbuf;
    fstat(fd, &statbuf);

    // 小火车发送文件长度给服务端
    Train train;
    train.length = sizeof(statbuf.st_size);
    memcpy(train.data, &statbuf.st_size, train.length);
    send(netfd, &train, sizeof(int) + train.length, MSG_NOSIGNAL);

    // 接收文件内容并写入本地
    char buf[1024] = {0};
    int length;
    while(1)
    {   
        recvN(netfd, &length, sizeof(length));
        if(length == 0)  
        {   
            break;
        }   
        bzero(buf, sizeof(buf));
        recvN(netfd, buf, length);
        write(fd, buf, length);
    }

    close(fd);

    return 0;
}

int sendFile(const char* filename, int netfd)
{
    // 打开文件
    int fd = open(filename, O_RDWR);

    // 小火车发送文件内容
    Train train;                            
    bzero(&train, sizeof(train));
    while(1)
    {
        bzero(&train, sizeof(train));
        train.length = read(fd, train.data, sizeof(train.data));
        send(netfd, &train, sizeof(int) + train.length, MSG_NOSIGNAL);
        if(train.length == 0)
        {
            break;
        }
    }

    return 0;
}
